<script setup>
import { ref, nextTick, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { sendChatMessage, sendChatMessageStream } from '@/api/ai'
import { marked } from 'marked'

// 配置 marked
marked.setOptions({
  breaks: true, // 支持换行
  gfm: true // 启用 GitHub 风格的 Markdown
})

// Markdown 渲染函数
const renderMarkdown = (content) => {
  return marked.parse(content || '')
}

// 当前会话 ID
const currentSessionId = ref(Date.now())

// 聊天消息列表
const messages = ref([
  {
    id: 1,
    type: 'ai',
    content:
      '您好！我是您的AI旅行助手 🌏，很高兴为您服务！\n\n我可以帮您：\n✈️ 智能规划旅行路线\n🗺️ 推荐热门景点和美食\n💰 制定旅行预算\n📅 安排最佳行程\n🎯 回答旅行相关问题\n\n请告诉我您想去哪里旅行？',
    timestamp: new Date().toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
])

// 历史记录
const chatHistory = ref([])

// 加载历史记录
const loadHistory = () => {
  const saved = localStorage.getItem('ai_chat_history')
  if (saved) {
    try {
      chatHistory.value = JSON.parse(saved)
    } catch (e) {
      console.error('加载历史记录失败:', e)
      chatHistory.value = []
    }
  }
}

// 保存当前对话到历史
const saveToHistory = () => {
  const userMessages = messages.value.filter((m) => m.type === 'user')
  if (userMessages.length === 0) return

  const firstUserMsg = userMessages[0].content
  const title =
    firstUserMsg.length > 30
      ? firstUserMsg.substring(0, 30) + '...'
      : firstUserMsg

  const existingIndex = chatHistory.value.findIndex(
    (h) => h.id === currentSessionId.value
  )

  const historyItem = {
    id: currentSessionId.value,
    title: title,
    messages: messages.value,
    timestamp: new Date().toISOString(),
    messageCount: userMessages.length
  }

  if (existingIndex !== -1) {
    chatHistory.value[existingIndex] = historyItem
  } else {
    chatHistory.value.unshift(historyItem)
  }

  if (chatHistory.value.length > 50) {
    chatHistory.value = chatHistory.value.slice(0, 50)
  }

  localStorage.setItem('ai_chat_history', JSON.stringify(chatHistory.value))
}

// 加载历史对话
const loadHistorySession = (session) => {
  currentSessionId.value = session.id
  messages.value = session.messages
  scrollToBottom()
}

// 删除历史记录
const deleteHistory = (sessionId) => {
  chatHistory.value = chatHistory.value.filter((h) => h.id !== sessionId)
  localStorage.setItem('ai_chat_history', JSON.stringify(chatHistory.value))
}

// 开始新对话
const startNewChat = () => {
  currentSessionId.value = Date.now()
  messages.value = [
    {
      id: 1,
      type: 'ai',
      content:
        '您好！我是您的AI旅行助手 🌏，很高兴为您服务！\n\n我可以帮您：\n✈️ 智能规划旅行路线\n🗺️ 推荐热门景点和美食\n💰 制定旅行预算\n📅 安排最佳行程\n🎯 回答旅行相关问题\n\n请告诉我您想去哪里旅行？',
      timestamp: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  ]
}

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`

  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// 组件挂载时加载历史记录
onMounted(() => {
  loadHistory()
})

// 用户输入
const userInput = ref('')

// 聊天容器引用
const chatContainerRef = ref(null)

// 快捷问题列表
const quickQuestions = ref([
  {
    icon: '🏖️',
    text: '推荐三亚3日游行程',
    query: '帮我规划一个三亚3天2晚的旅游行程，想去海边玩'
  },
  {
    icon: '🍜',
    text: '成都必吃美食',
    query: '去成都旅游有哪些必吃的美食推荐？'
  },
  {
    icon: '💰',
    text: '预算规划建议',
    query: '两个人去云南玩7天大概需要多少预算？'
  },
  {
    icon: '🎒',
    text: '旅行必备清单',
    query: '出门旅行需要准备哪些东西？给我一个清单'
  }
])

// 是否正在输入
const isTyping = ref(false)

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainerRef.value) {
      chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight
    }
  })
}

// 使用流式响应
const useStream = ref(true)

// 发送消息
const sendMessage = async () => {
  const content = userInput.value.trim()
  if (!content) {
    ElMessage.warning('请输入您的问题')
    return
  }

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: content,
    timestamp: new Date().toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  messages.value.push(userMessage)
  userInput.value = ''
  scrollToBottom()

  // 调用真实 AI API
  isTyping.value = true

  try {
    if (useStream.value) {
      // 使用流式响应
      await getAiResponseStream()
    } else {
      // 使用普通响应
      await getAiResponse()
    }
  } catch (error) {
    isTyping.value = false
    handleApiError(error)
  }
}

// 获取 AI 回复（普通模式）
const getAiResponse = async () => {
  try {
    const reply = await sendChatMessage(messages.value)

    isTyping.value = false

    const aiResponse = {
      id: Date.now(),
      type: 'ai',
      content: reply,
      timestamp: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    messages.value.push(aiResponse)
    scrollToBottom()

    // 保存到历史记录
    saveToHistory()
  } catch (error) {
    throw error
  }
}

// 打字机效果配置
const typewriterSpeed = ref(30) // 每个字符显示间隔（毫秒），可调整 20-50
let typewriterQueue = [] // 待显示的字符队列
let isTypewriting = false // 是否正在打字（避免与 isTyping 冲突）

// 打字机效果函数
const typewriterEffect = async (aiResponse) => {
  if (isTypewriting) return
  isTypewriting = true

  while (typewriterQueue.length > 0) {
    const char = typewriterQueue.shift()
    aiResponse.content += char

    // 触发响应式更新
    const lastIndex = messages.value.length - 1
    messages.value[lastIndex] = { ...aiResponse }
    scrollToBottom()

    // 延迟，创建打字机效果
    await new Promise((resolve) => setTimeout(resolve, typewriterSpeed.value))
  }

  isTypewriting = false
}

// 获取 AI 回复（流式模式）
const getAiResponseStream = async () => {
  console.log('开始流式响应处理...')

  // 重置打字机队列
  typewriterQueue = []
  isTypewriting = false

  // 创建一个新的 AI 消息对象
  const aiResponse = {
    id: Date.now(),
    type: 'ai',
    content: '',
    timestamp: new Date().toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  isTyping.value = false
  messages.value.push(aiResponse)
  console.log('已添加空 AI 消息到列表')

  try {
    await sendChatMessageStream(
      messages.value.slice(0, -1), // 不包含刚添加的空消息
      (chunk) => {
        // 将接收到的字符加入队列
        for (const char of chunk) {
          typewriterQueue.push(char)
        }

        // 如果还未开始打字，启动打字机效果
        if (!isTypewriting) {
          typewriterEffect(aiResponse)
        }
      }
    )

    // 等待所有字符显示完成
    while (typewriterQueue.length > 0 || isTypewriting) {
      await new Promise((resolve) => setTimeout(resolve, 50))
    }

    console.log('流式响应处理完成，最终内容:', aiResponse.content)

    // 保存到历史记录
    saveToHistory()
  } catch (error) {
    console.error('流式响应处理出错:', error)
    // 如果出错，移除这条空消息
    messages.value.pop()
    throw error
  }
}

// 处理 API 错误
const handleApiError = (error) => {
  console.error('AI API Error:', error)

  const errorMessage = error.message || '发生未知错误'

  ElMessage.error('AI 回复失败：' + errorMessage)

  // 添加错误提示消息
  const errorResponse = {
    id: Date.now(),
    type: 'ai',
    content: `抱歉，我遇到了一些问题：${errorMessage}\n\n请稍后重试。`,
    timestamp: new Date().toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  messages.value.push(errorResponse)
  scrollToBottom()
}

// 快捷提问
const handleQuickQuestion = (question) => {
  userInput.value = question.query
  sendMessage()
}

// 清空对话
const clearChat = () => {
  messages.value = [
    {
      id: 1,
      type: 'ai',
      content: '对话已清空！有什么可以帮您的吗？',
      timestamp: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  ]
}

// 键盘事件
const handleKeyPress = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}
</script>

<template>
  <div class="ai-assistant-container">
    <div class="history-sidebar">
      <div class="sidebar-header">
        <h2>历史记录</h2>
        <el-button type="primary" @click="startNewChat" size="small">
          ➕ 新对话
        </el-button>
      </div>

      <div class="history-list">
        <div v-if="chatHistory.length === 0" class="empty-history">
          <p>暂无历史记录</p>
          <p class="hint">开始聊天后自动保存</p>
        </div>

        <div
          v-for="session in chatHistory"
          :key="session.id"
          :class="['history-item', { active: session.id === currentSessionId }]"
          @click="loadHistorySession(session)"
        >
          <div class="history-item-content">
            <div class="history-title">💬 {{ session.title }}</div>
            <div class="history-meta">
              <span>{{ session.messageCount }} 条</span>
              <span>{{ formatDate(session.timestamp) }}</span>
            </div>
          </div>
          <button
            @click.stop="deleteHistory(session.id)"
            class="delete-btn"
            title="删除"
          >
            🗑️
          </button>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div ref="chatContainerRef" class="chat-container">
        <div class="messages-wrapper">
          <div v-if="messages.length === 1" class="welcome-section">
            <div class="welcome-icon">✨</div>
            <h1 class="welcome-title">AI旅行助手</h1>
            <p class="welcome-subtitle">
              我可以帮您规划行程、推荐景点、解答旅行相关问题
            </p>

            <div class="quick-questions">
              <div
                v-for="question in quickQuestions"
                :key="question.text"
                class="question-card"
                @click="handleQuickQuestion(question)"
              >
                <span class="question-icon">{{ question.icon }}</span>
                <span class="question-text">{{ question.text }}</span>
              </div>
            </div>
          </div>

          <div
            v-for="message in messages"
            :key="message.id"
            :class="['message-row', message.type]"
          >
            <div class="message-wrapper">
              <div v-if="message.type === 'ai'" class="message-avatar">
                <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                  <rect width="28" height="28" rx="6" fill="#10a37f" />
                  <path
                    d="M14 8v12M8 14h12"
                    stroke="white"
                    stroke-width="2"
                    stroke-linecap="round"
                  />
                </svg>
              </div>
              <div class="message-content">
                <div
                  class="message-text"
                  v-html="
                    message.type === 'ai'
                      ? renderMarkdown(message.content)
                      : message.content.replace(/\n/g, '<br>')
                  "
                ></div>
              </div>
            </div>
          </div>

          <div v-if="isTyping" class="message-row ai">
            <div class="message-wrapper">
              <div class="message-avatar">
                <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                  <rect width="28" height="28" rx="6" fill="#10a37f" />
                  <path
                    d="M14 8v12M8 14h12"
                    stroke="white"
                    stroke-width="2"
                    stroke-linecap="round"
                  />
                </svg>
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <div class="input-wrapper">
        <div class="input-container">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="1"
            :autosize="{ minRows: 1, maxRows: 6 }"
            placeholder="Send a message..."
            @keypress="handleKeyPress"
            class="message-input"
          />
          <button
            :disabled="!userInput.trim()"
            @click="sendMessage"
            class="send-button"
          >
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M3 10L17 3L10 17L9 11L3 10Z" fill="currentColor" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.ai-assistant-container {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
  background: #f7f7f8;
  overflow: hidden;
}

// 左侧固定历史记录侧边栏
.history-sidebar {
  width: 260px;
  background: #f7f7f8;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  height: 100%;

  .sidebar-header {
    padding: 20px 16px;
    border-bottom: 1px solid #e5e5e5;
    background: white;

    h2 {
      margin: 0 0 12px 0;
      font-size: 16px;
      font-weight: 600;
      color: #202123;
    }
  }

  .history-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.1);
      border-radius: 3px;
    }

    .empty-history {
      text-align: center;
      padding: 40px 20px;
      color: #9ca3af;

      p {
        margin: 0;
      }
    }

    .history-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px;
      margin-bottom: 4px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background: #f7f7f8;

        .delete-btn {
          opacity: 1;
        }
      }

      &.active {
        background: #e8f5e9;
      }

      .history-item-content {
        flex: 1;
        min-width: 0;

        .history-title {
          font-size: 14px;
          color: #202123;
          font-weight: 500;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .history-meta {
          font-size: 12px;
          color: #9ca3af;
          display: flex;
          gap: 8px;

          span {
            &:not(:last-child)::after {
              content: '·';
              margin-left: 8px;
              color: #d1d5db;
            }
          }
        }
      }

      .delete-btn {
        opacity: 0;
        background: none;
        border: none;
        font-size: 16px;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.2s ease;

        &:hover {
          background: #fee2e2;
        }
      }
    }

    .hint {
      font-size: 12px;
      color: #d1d5db;
      margin-top: 8px;
    }
  }
}

// 主聊天区域
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  background: white;
}

// 聊天容器
.chat-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 180px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.2);
    }
  }
}

.messages-wrapper {
  max-width: 768px;
  margin: 0 auto;
  padding: 24px;
}

// 欢迎区域
.welcome-section {
  padding: 48px 24px;
  text-align: center;

  .welcome-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  .welcome-title {
    font-size: 32px;
    font-weight: 600;
    color: #202123;
    margin: 0 0 12px 0;
  }

  .welcome-subtitle {
    font-size: 16px;
    color: #6e6e80;
    margin: 0 0 32px 0;
  }
}

// 快捷问题
.quick-questions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 12px;
  margin-top: 24px;

  .question-card {
    padding: 16px;
    background: white;
    border: 1px solid #e5e5e5;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 12px;
    text-align: left;

    .question-icon {
      font-size: 20px;
      flex-shrink: 0;
    }

    .question-text {
      flex: 1;
      font-size: 14px;
      color: #202123;
      font-weight: 500;
    }

    &:hover {
      background: #f7f7f8;
      border-color: #d0d0d0;
    }
  }
}

// 消息行
.message-row {
  margin-bottom: 24px;
  animation: fadeIn 0.3s ease;

  &.ai {
    background: white;
    border-bottom: 1px solid #e5e5e5;
    margin-left: -24px;
    margin-right: -24px;
    padding: 24px;
  }

  &.user {
    .message-wrapper {
      justify-content: flex-end;
    }
  }
}

.message-wrapper {
  max-width: 768px;
  margin: 0 auto;
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.message-avatar {
  width: 28px;
  height: 28px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-text {
  font-size: 16px;
  line-height: 1.75;
  color: #374151;
  white-space: pre-wrap;
  word-wrap: break-word;

  :deep(br) {
    display: block;
    content: '';
    margin-top: 8px;
  }

  // Markdown 样式
  :deep(h1) {
    font-size: 24px;
    font-weight: 600;
    margin: 20px 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #e5e5e5;
    color: #202123;
  }

  :deep(h2) {
    font-size: 20px;
    font-weight: 600;
    margin: 18px 0 12px 0;
    color: #202123;
  }

  :deep(h3) {
    font-size: 18px;
    font-weight: 600;
    margin: 16px 0 10px 0;
    color: #374151;
  }

  :deep(h4),
  :deep(h5),
  :deep(h6) {
    font-size: 16px;
    font-weight: 600;
    margin: 14px 0 8px 0;
    color: #374151;
  }

  :deep(p) {
    margin: 12px 0;
    line-height: 1.75;
  }

  :deep(strong) {
    font-weight: 600;
    color: #202123;
  }

  :deep(em) {
    font-style: italic;
  }

  :deep(ul),
  :deep(ol) {
    margin: 12px 0;
    padding-left: 24px;
  }

  :deep(li) {
    margin: 6px 0;
    line-height: 1.6;
  }

  :deep(ul li) {
    list-style-type: disc;
  }

  :deep(ol li) {
    list-style-type: decimal;
  }

  :deep(code) {
    background: #f6f8fa;
    padding: 2px 6px;
    border-radius: 4px;
    font-family: 'Monaco', 'Consolas', 'Courier New', monospace;
    font-size: 14px;
    color: #e83e8c;
  }

  :deep(pre) {
    background: #f6f8fa;
    padding: 16px;
    border-radius: 8px;
    overflow-x: auto;
    margin: 12px 0;

    code {
      background: none;
      padding: 0;
      color: #24292e;
      font-size: 14px;
      line-height: 1.5;
    }
  }

  :deep(blockquote) {
    border-left: 4px solid #10a37f;
    padding-left: 16px;
    margin: 12px 0;
    color: #6e6e80;
    font-style: italic;
  }

  :deep(a) {
    color: #10a37f;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 12px 0;

    th,
    td {
      border: 1px solid #e5e5e5;
      padding: 8px 12px;
      text-align: left;
    }

    th {
      background: #f6f8fa;
      font-weight: 600;
    }

    tr:hover {
      background: #fafafa;
    }
  }

  :deep(hr) {
    border: none;
    border-top: 1px solid #e5e5e5;
    margin: 20px 0;
  }
}

// 输入正在输入动画
.typing-indicator {
  display: flex;
  gap: 6px;
  padding: 12px 0;

  span {
    width: 8px;
    height: 8px;
    background: #9ca3af;
    border-radius: 50%;
    animation: typing 1.4s infinite;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%,
  60%,
  100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-8px);
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 输入区域
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, #f7f7f8 85%, transparent);
  padding: 32px 0 24px;
  z-index: 10;
}

.input-wrapper {
  max-width: 768px;
  margin: 0 auto;
  padding: 0 24px;
}

.input-container {
  position: relative;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 12px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;

  &:focus-within {
    border-color: #10a37f;
    box-shadow: 0 0 0 3px rgba(16, 163, 127, 0.1);
  }

  .message-input {
    :deep(.el-textarea__inner) {
      border: none;
      border-radius: 12px;
      font-size: 16px;
      line-height: 24px;
      padding: 12px 52px 12px 16px;
      resize: none;
      background: transparent;
      color: #374151;

      &:focus {
        box-shadow: none;
        outline: none;
      }

      &::placeholder {
        color: #9ca3af;
      }
    }
  }

  .send-button {
    position: absolute;
    right: 12px;
    bottom: 12px;
    width: 32px;
    height: 32px;
    border-radius: 6px;
    border: none;
    background: #10a37f;
    color: white;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;

    &:hover:not(:disabled) {
      background: #0d8c6a;
    }

    &:disabled {
      background: #f3f4f6;
      color: #d1d5db;
      cursor: not-allowed;
    }

    svg {
      width: 20px;
      height: 20px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .messages-wrapper {
    padding: 16px 16px 32px 16px;
  }

  .welcome-section {
    padding: 32px 16px;

    .welcome-title {
      font-size: 24px;
    }

    .welcome-subtitle {
      font-size: 14px;
    }
  }

  .quick-questions {
    grid-template-columns: 1fr;
  }

  .message-row.ai {
    margin-left: -16px;
    margin-right: -16px;
    padding: 16px;
  }

  .input-wrapper {
    padding: 0 16px;
  }

  .input-area {
    padding: 20px 0 16px;
  }

  .message-text {
    font-size: 15px;
  }
}
</style>
